import { _decorator, Component, Node, EventTouch, Label, Sprite, assetManager, ImageAsset, SpriteFrame, UITransform, director, Prefab, instantiate } from 'cc';
const { ccclass, property } = _decorator;
import { GameRoot } from './GameRoot';
import { TaKuSDK } from './TaKuSDK';
import { UserApi } from './api/user';
import { UserModel } from './models/user';
import { ENV } from './config/main';
import { RecordItem } from './RecordItem';
@ccclass('Profile')
export class Profile extends Component {

    @property(Node)
    private re_btn: Node = null;

    @property(Node)
    private ad_btn: Node = null;


    @property(Label)
    private ad_count: Label = null;

    @property(Label)
    private uid: Label = null;

    @property(Sprite)
    private avatar: Sprite = null;

    @property(Node)
    private closeBtn: Node = null;

    @property(Node)
    private logoutbtn: Node = null;

    @property(Prefab)
    private recordItem: Prefab = null;

    // 容器
    @property(Node)
    private recordContainer: Node = null;



    start() {
        // 先移除可能存在的事件监听器
        this.re_btn.off(Node.EventType.TOUCH_START);
        this.ad_btn.off(Node.EventType.TOUCH_START);
        this.closeBtn.off(Node.EventType.TOUCH_START);
        this.logoutbtn.off(Node.EventType.TOUCH_START);
        
        // 重新注册
        this.re_btn.on(Node.EventType.TOUCH_START, this.onReBtnClick, this);
        this.ad_btn.on(Node.EventType.TOUCH_START, this.onAdBtnClick, this);
        this.closeBtn.on(Node.EventType.TOUCH_START, this.onCloseBtnClick, this);
        this.logoutbtn.on(Node.EventType.TOUCH_START, this.onLogoutBtnClick, this);
    }

    onLogoutBtnClick(){
        console.log("onLogoutBtnClick");
        if(CC_DEBUG){
            UserModel.getInstance().clearUserInfo();
            director.loadScene('login');
            return;
        }
        UserApi.logout().then(() => {
            UserModel.getInstance().clearUserInfo();
            director.loadScene('login');
        });
    }

    /**
     * 关闭按钮点击
     */
    onCloseBtnClick(){
        this.node.parent.getComponent(GameRoot).onCloseUserLayer();
    }

    showCloseBtn(){
        this.closeBtn.active = true;
    }

    hideCloseBtn(){
        this.closeBtn.active = false;
    }

    loadUserAdInfo(){

        let appid = ENV.SDK.ANDROID.APP_ID;
        if (cc.sys.os === cc.sys.OS.IOS) {           
            appid = ENV.SDK.IOS.APP_ID;
        } else if (cc.sys.os === cc.sys.OS.ANDROID) {
            appid = ENV.SDK.ANDROID.APP_ID;
        }

        UserApi.getUserAdInfo(appid).then((res) => {
            console.log("getUserAdInfo", JSON.stringify(res));

            if(res.avatar && res.avatar.startsWith("http")){
                this.loadAvatarFromUrl(res.avatar);
            }
            if(res.today_ad_count){
                this.ad_count.string = `今日AD数量：${res.today_ad_count}`;
            }
            if(res.user_id){
                this.uid.string = `UID：${res.user_id}`;
            }

            // 填充记录
            if(res.today_ads && res.today_ads.length > 0){
                this.recordContainer.removeAllChildren();
                for(let i = 0; i < res.today_ads.length; i++){
                    const todayAd = res.today_ads[i];
                    const recordItem = instantiate(this.recordItem);
                    this.recordContainer.addChild(recordItem);
                    recordItem.getComponent(RecordItem).setData(todayAd.create_time);
                }
            }
        });
    }

    /**

     * 从URL加载头像

     * @param url 头像URL

     */

    loadAvatarFromUrl(url: string) {
        if (!url) {
            console.warn('头像URL为空');
            return;
        }

        assetManager.loadRemote<ImageAsset>(url, {ext: '.png'}, (err, imageAsset) => {
            if (err) {
                console.error('加载头像失败:', err);
                return;
            }

            // 将ImageAsset转换为SpriteFrame并设置到头像
            const spriteFrame = SpriteFrame.createWithImage(imageAsset);
            if (this.avatar && spriteFrame) {
                this.avatar.spriteFrame = spriteFrame;
                // 调整图片适应容器
                this.adjustAvatarSize();
            }
        });

    }

    /**

     * 调整头像大小以适应容器

     */

    adjustAvatarSize() {
        if (!this.avatar || !this.avatar.spriteFrame) return;
        const transform = this.avatar.node.getComponent(UITransform);
        if (!transform) return;
        // 获取节点宽高
        const nodeWidth = transform.width;
        const nodeHeight = transform.height;
        // 获取图片宽高
        const imgWidth = this.avatar.spriteFrame.width;
        const imgHeight = this.avatar.spriteFrame.height;

        // 计算宽高比
        const nodeRatio = nodeWidth / nodeHeight;
        const imgRatio = imgWidth / imgHeight;
        // 根据宽高比调整缩放和填充模式
        if (imgRatio > nodeRatio) {
            // 图片比容器宽，以高度为基准
            this.avatar.type = Sprite.Type.SIMPLE;
            this.avatar.sizeMode = Sprite.SizeMode.CUSTOM;
            this.avatar.trim = false;

        } else {
            this.avatar.type = Sprite.Type.SIMPLE;
            this.avatar.sizeMode = Sprite.SizeMode.CUSTOM;
            this.avatar.trim = false;
        }

    }



    onReBtnClick(event: EventTouch, customEventData: string){
        this.node.parent.getComponent(GameRoot).reStartGame();
    }

    onAdBtnClick(event: EventTouch, customEventData: string){
        try{
            TaKuSDK.getInstance().showRewardedVideoAd();
        }catch(e){
            console.log("showRewardedVideoAd error", e);
        }


    }
    

}


